package com.sql.api;

import com.sql.bean.TableInfo;
import com.sql.common.intc.SqlTypeConvert;
import com.sql.common.util.ConnectionFactory;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Searcher {

    private static final String tableArr[] = new String[]{"TABLE"};

    private ConnectionFactory connectionFactory;

    public Searcher(ConnectionFactory connectionFactory){
        this.connectionFactory = connectionFactory;
    }

    public void setConnectionFactory(ConnectionFactory connectionFactory){
        this.connectionFactory=connectionFactory;
    }

    public List<String> showTables() throws Exception{
        List<String> list = new ArrayList<>(20);
        Connection conn = connectionFactory.getConnection(null);
        DatabaseMetaData d = conn.getMetaData();
        ResultSet resultSet = d.getTables(null, connectionFactory.getUserNameUpper(), null, tableArr);
        while (resultSet.next()) {
            list.add(resultSet.getString("TABLE_NAME"));
        }
        return list;
    }

    public List<TableInfo> showTableInfo(String table) throws Exception {
//        table=table.toUpperCase();
        List<TableInfo> list = new ArrayList<>(20);
        Connection conn = connectionFactory.getConnection(null);
        DatabaseMetaData d = conn.getMetaData();
        ResultSet resultSet = d.getTables(null, connectionFactory.getUserNameUpper(), table, tableArr);
        while (resultSet.next()) {
            String tableName = resultSet.getString("TABLE_NAME");
            if (tableName.equals(table)) {
                TableInfo tableInfo = new TableInfo();
                tableInfo.setTableColumn(tableName);
                tableInfo.setColumnType("表信息");
                tableInfo.setColumCommon(resultSet.getString("REMARKS"));
                list.add(tableInfo);
                ResultSet rs = conn.getMetaData().getColumns(null, conn.getMetaData().getUserName().toUpperCase(), tableName, "%");
                while (rs.next()) {
                    tableInfo = new TableInfo();
                    tableInfo.setTableColumn(rs.getString("COLUMN_NAME"));
                    tableInfo.setColumnType(rs.getString("TYPE_NAME"));
                    tableInfo.setColumCommon(rs.getString("REMARKS"));
                    list.add(tableInfo);
                }
            }
        }
        return list;
    }

    public List<Map<String,Object>> selectTable(String sql,Map<Integer,SqlTypeConvert> mapTypeConvert) throws Exception{
        List<Map<String,Object>> list = (List<Map<String, Object>>) connectionFactory.getDao().getBySql(Map.class,sql,mapTypeConvert);
        return list;
    }

    public int updateOrDelete(String sql) throws Exception{
        return connectionFactory.getDao().getPreparedStatement(sql).executeUpdate();
    }

}
